import plugin from '../../../lib/plugins/plugin.js'
import Mc from "../components/Code.js";
import mcConfig from "../components/mcConfig.js";
import Render from '../model/render.js'

export class Userxinxi extends plugin {
    constructor() {
        super({
            name: "鸣潮信息查询",
            event: "message",
            priority: 666666,
            rule: [
                {
                    reg: "^#?(明朝|鸣潮)卡片.*$",
                    fnc: "xinxi"
                }
            ]
        })
    }

    async xinxi(e) {
        let accountList = JSON.parse(await redis.get(`Yunzai:mingchao:users:${e.user_id}`)) || await mcConfig.getUserConfig(e.user_id);
        const mc = new Mc();

        const match = e.msg.replace(/^#?(明朝|鸣潮)卡片/, '').match(/^\d{9}$/);

        if (!accountList.length) {
            if (match) {
                const publicCookie = await mc.getPublicCookie();
                if (!publicCookie) {
                    return await e.reply('当前没有Ck可用，请先绑定鸣潮账号');
                } else {
                    accountList.push(publicCookie);
                }
            } else {
                return await e.reply('当前没有绑定任何账号，请先绑定鸣潮账号');
            }
        }

        let data = [];
        let deleteroleId = [];

        await Promise.all(accountList.map(async (account) => {
            const usability = await mc.isAvailable(account.token);

            if (!usability) {
                data.push({ message: `账号 ${account.roleId} 的Token已失效\n请重新绑定鸣潮账号` });
                deleteroleId.push(account.roleId);
                return;
            }

            if (match) {
                account.roleId = match[0];
            }

            const [baseData, roleData] = await Promise.all([
                mc.getBaseData(account.serverId, account.roleId, account.token),
                mc.getRoleData(account.serverId, account.roleId, account.token)
            ]);

            if (!baseData.status || !roleData.status) {
                data.push({ message: baseData.msg || roleData.msg });
            } else {
                const imageCard = await Render.userInfo(baseData.data, roleData.data)
                data.push({ message: imageCard });
            }
        }));

        if (deleteroleId.length) {
            let newAccountList = accountList.filter(account => !deleteroleId.includes(account.roleId));
            mcConfig.setUserConfig(e.user_id, newAccountList);
        }

        if (data.length === 1) {
            await e.reply(data[0].message);
            return true;
        }

        await e.reply(Bot.makeForwardMsg([{ message: `用户 ${e.user_id}` }, ...data]));
        return true;
    }
}